package com.youlai.boot.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.youlai.boot.system.enums.DictCodeEnum;
import com.youlai.boot.system.model.entity.DictData;
import com.youlai.boot.system.model.vo.SpotCountDTO;
import com.youlai.boot.system.model.vo.SpotCountExcelVO;
import com.youlai.boot.system.service.DictDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.system.mapper.SpotCountMapper;
import com.youlai.boot.system.service.SpotCountService;
import com.youlai.boot.system.model.entity.SpotCount;
import com.youlai.boot.system.model.form.SpotCountForm;
import com.youlai.boot.system.model.query.SpotCountQuery;
import com.youlai.boot.system.model.vo.SpotCountVO;
import com.youlai.boot.system.converter.SpotCountConverter;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

/**
 * 统计服务实现类
 *
 * @author lwb
 * @since 2025-07-01 22:00
 */
@Service
@RequiredArgsConstructor
public class SpotCountServiceImpl extends ServiceImpl<SpotCountMapper, SpotCount> implements SpotCountService {

    private final SpotCountConverter spotCountConverter;

    private final DictDataService dictDataService;

    /**
     * 获取统计分页列表
     *
     * @param queryParams 查询参数
     * @return {@link IPage<SpotCountVO>} 统计分页列表
     */
    @Override
    public IPage<SpotCountVO> getSpotCountPage(SpotCountQuery queryParams) {
        Page<SpotCountVO> pageVO = this.baseMapper.getSpotCountPage(new Page<>(queryParams.getPageNum(), queryParams.getPageSize()), queryParams);
        return pageVO;
    }

    /**
     * 获取统计表单数据
     *
     * @param id 统计ID
     * @return
     */
    @Override
    public SpotCountForm getSpotCountFormData(Long id) {
        return baseMapper.getSpotCountFormData(id);
    }

    /**
     * 新增统计
     *
     * @param formData 统计表单对象
     * @return
     */
    @Override
    public boolean saveSpotCount(SpotCountForm formData) {
        SpotCount entity = spotCountConverter.toEntity(formData);
        return this.save(entity);
    }

    /**
     * 更新统计
     *
     * @param id       统计ID
     * @param formData 统计表单对象
     * @return
     */
    @Override
    public boolean updateSpotCount(Long id, SpotCountForm formData) {
        SpotCount entity = spotCountConverter.toEntity(formData);
        return this.updateById(entity);
    }

    /**
     * 删除统计
     *
     * @param ids 统计ID，多个以英文逗号(,)分割
     * @return
     */
    @Override
    public boolean deleteSpotCounts(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的统计数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(",")).map(Long::parseLong).toList();
        return this.removeByIds(idList);
    }

    @Override
    public List<SpotCountExcelVO> export(SpotCountQuery queryParams) {
        List<SpotCountExcelVO> list = this.baseMapper.exportList(queryParams);
        if (CollUtil.isNotEmpty(list)) {

            //获取权限的字典数据
            List<DictData> dictList = dictDataService.list(new LambdaQueryWrapper<DictData>().eq(DictData::getDictCode, DictCodeEnum.OPERATETYPE.getValue()));
            Map<String, List<DictData>> dictMap = dictList.stream().collect(Collectors.groupingBy(DictData::getDictCode));

            AtomicInteger index = new AtomicInteger(1);
            list.forEach(item -> {

                List<DictData> landTypeDictData = dictMap.get(DictCodeEnum.OPERATETYPE.getValue());
                if (CollUtil.isNotEmpty(landTypeDictData)) {
                    DictData dictData = landTypeDictData.stream().filter(data -> data.getValue().equals(String.valueOf(item.getOperateType()))).findFirst().orElse(null);
                    item.setOperateType(dictData != null ? dictData.getLabel() : "");
                }

                item.setSn(String.valueOf(index.getAndIncrement()));
            });
        }
        return list;
    }

    @Override
    public List<SpotCountDTO> getCount(SpotCountQuery queryParams) {
        List<SpotCountForm> countList = baseMapper.getCount(queryParams);
        if (CollUtil.isEmpty(countList)) {
            return Collections.emptyList();
        }

        Map<Long, List<SpotCountForm>> countMap = countList.stream().collect(Collectors.groupingBy(SpotCountForm::getCategoryId));
        Set<Map.Entry<Long, List<SpotCountForm>>> entrySet = countMap.entrySet();

        List<SpotCountDTO> list = new ArrayList<>();
        for (Map.Entry<Long, List<SpotCountForm>> entry : entrySet) {
            List<SpotCountForm> value = entry.getValue();
            SpotCountForm form = value.get(0);
            //操作类型1出票2预售
            Integer outNum = 0;
            SpotCountForm outCountForm = value.stream().filter(item -> item.getOperateType() == 1).findFirst().orElse(null);
            if (Objects.nonNull(outCountForm)) {
                outNum = outCountForm.getNum();
            }
            Integer sellNum = 0;
            SpotCountForm sellCountForm = value.stream().filter(item -> item.getOperateType() == 2).findFirst().orElse(null);
            if (Objects.nonNull(sellCountForm)) {
                sellNum = sellCountForm.getNum();
            }
            SpotCountDTO dto = new SpotCountDTO();
            dto.setCategoryName(form.getCategoryName());
            dto.setOutNum(outNum);
            dto.setSellNum(sellNum);
            list.add(dto);
        }
        return list;
    }
}
